import sparkMD5 from 'spark-md5'
import type { FileChunkResult } from './chunkFile'

async function calculateFileHash(fileChunkList: Array<FileChunkResult>) {
  return new Promise(resolve => {
    const spark = new sparkMD5()
    for (const chunk of fileChunkList) {
      spark.append(chunk.chunk_hash)
    }
    resolve(spark.end())
  })
}

self.onmessage = async e => {
  const { fileChunkList } = e.data
  const fileHash = await calculateFileHash(fileChunkList)
  postMessage(fileHash)
}